﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.UserManager;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.SysUserExt;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;
using System.Security.Claims;
using SJ.Platform.EFCore.Model.RoleManager;
using Amazon.Runtime.Internal;
using Microsoft.EntityFrameworkCore;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Common;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SJ.Platform.Api.Controllers.UserManager
{
    /// <summary>
    /// 用户操作接口
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/User")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class UserManagerController : ControllerBase
    {
        private readonly SJDBContext _context;
        private readonly Sys_UserHandle sys_UserHandle;
        private readonly Sys_LoginHandle login_UserHandle;
        private readonly Sys_OrgHandle sys_OrgHandle;
        private readonly Sys_RoleHandle sys_RoleHandle;
        private readonly ICurrentUser _currentUser;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public UserManagerController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            _context = dbContext;
            sys_UserHandle = new Sys_UserHandle(dbContext);
            login_UserHandle = new Sys_LoginHandle(dbContext);
            sys_OrgHandle = new Sys_OrgHandle(dbContext);
            sys_RoleHandle = new Sys_RoleHandle(dbContext);
            _currentUser = currentUser;
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateUserAsync")]
        public async Task<IActionResult> CreateUserAsync([FromBody] SysUserAddExtend model)
        {
            // 调用业务逻辑层保存用户信息
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    // 创建 SysUser 实体对象
                    var sysUser = new SysUser
                    {
                        Id = Guid.NewGuid().ToString(),
                        RealName = model.RealName,
                        OrgId = model.OrgId,
                        OrgName = model.OrgName,
                        Sex = model.Sex,
                        Birthday = model.Birthday,
                        IsUsed = model.IsUsed,
                        AddTime = DateTime.Now,
                        AddUserId = _currentUser.UserId,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };
                    //登录账号
                    var loginUser = new SysLogin
                    {
                        Id = sysUser.Id,
                        LoginName = model.LoginName,
                        Password = model.Password,
                        IsUsed = model.IsUsed
                    };
                    return await sys_UserHandle.CreateAsync(sysUser) && await login_UserHandle.CreateAsync(loginUser);
                });
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "用户添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "用户添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateUserAsync")]
        public async Task<IActionResult> UpdateUserAsync([FromBody] SysUserAddExtend model)
        {
            // 调用业务逻辑层保存用户信息
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    // 创建 SysUser 实体对象
                    var sysUser = new SysUser
                    {
                        Id = model.Id,
                        RealName = model.RealName,
                        OrgId = model.OrgId,
                        OrgName = model.OrgName,
                        Sex = model.Sex,
                        Birthday = model.Birthday,
                        IsUsed = model.IsUsed,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };
                    //登录账号
                    var loginUser = new SysLogin
                    {
                        Id = sysUser.Id,
                        LoginName = model.LoginName,
                        IsUsed = model.IsUsed
                    };

                    return await sys_UserHandle.UpdateAsync(sysUser) && await login_UserHandle.UpdateAsync(loginUser);
                });
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "用户修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "用户修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByUserIdAsync/{userId}")]
        public async Task<IActionResult> DeleteByUserIdAsync(string userId)
        {
            try
            {
                bool result = await sys_UserHandle.DeleteByIdAsync(userId);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除用户" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除用户失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 根据组织机构获取用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetUserByOrgIdAsync")]
        public async Task<IActionResult> GetUserByOrgIdAsync([FromBody] ApiPageQueryRequest<SysUserAddExtend> request)
        {
            try
            {
                string orgId = request.Condition.OrgId;
                if((bool)request.Condition.SearchAll)
                {
                    var org = await sys_OrgHandle.GetAllAsync(o => string.IsNullOrWhiteSpace(o.Pid));
                    orgId = org[0].Id;
                }
                List<SysOrgExtend> orgList =  await sys_OrgHandle.GetAllByOrgId(orgId);

                if (orgList != null && orgList.Count > 0)
                {
                    var result = await sys_UserHandle.GetAllByOrgAsync((int)request.PageIndex, (int)request.PageSize, orgList, !string.IsNullOrWhiteSpace(request.Condition.RealName) ? c => c.RealName.Contains(request.Condition.RealName) : null);

                    return Ok(ApiPageQueryResponse<List<SysUserAddExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.usersExt)); // 返回成功的响应
                }
                else
                {
                    return Ok(ApiPageQueryResponse<List<SysUserAddExtend>>.SetResponse(ApiResponseStatus.NoData, "没有查询到数据", (int)request.PageIndex, (int)request.PageSize, 0, new List<SysUserAddExtend> { }));
                }
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<SysUserAddExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<SysUserAddExtend> { }));
            }
        }

        /// <summary>
        /// 根据角色获取用户
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet("GetUserByRoleIdAsync/{roleId}")]
        public async Task<IActionResult> GetUserByRoleIdAsync(string roleId)
        {
            try
            {
                var result = await sys_UserHandle.GetAllByRoleId(roleId);
                return Ok(ApiNormalResponse<List<SysUser>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<SysUser>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<SysUser> { }));
            }
        }

        /// <summary>
        /// 根据用户ID获取角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet("GetUserRolesByUserIdAsync/{userId}")]
        public async Task<IActionResult> GetUserRolesByUserIdAsync(string userId)
        {
            try
            {
                List<SysRole> result = await sys_RoleHandle.GetAllByUserIdAsync(userId);
                return Ok(ApiNormalResponse<List<SysRole>>.SetResponse(ApiResponseStatus.Success, "获取用户角色成功", result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<SysRole>>.SetResponse(ApiResponseStatus.BadRequest, "获取用户角色失败：" + ex.Message, new List<SysRole> { }));
            }
        }

        /// <summary>
        /// 配置用户角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roles">角色id</param>
        /// <returns></returns>
        [HttpGet("ConfigureUserRolesAsync/{userId}/{roles}")]
        public async Task<IActionResult> ConfigureUserRolesAsync(string userId, string roles)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    //先删除原有的角色配置
                    bool actionResult = await sys_RoleHandle.DeleteRelationByUserIdAsync(userId);

                    if (actionResult)
                    {
                        //再添加新的角色配置
                        List<SysRForeigntorole> list = new List<SysRForeigntorole>();
                        if (!string.IsNullOrWhiteSpace(roles))
                        {
                            string[] roleIds = roles.Split(',');
                            foreach (string id in roleIds)
                            {
                                list.Add(new SysRForeigntorole { Id = Guid.NewGuid().ToString(), ForeignId = userId, RoleId = id, ForeignType = 1, AddTime = DateTime.Now, AddUserId = _currentUser.UserId });
                            }
                        }
                        actionResult = list.Count > 0 && await sys_RoleHandle.ConfigureUserRolesAsync(list);
                    }
                    return actionResult;
                });
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "配置用户角色" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<SysRole>>.SetResponse(ApiResponseStatus.BadRequest, "配置用户角色失败：" + ex.Message, new List<SysRole> { }));
            }
        }
    }
}
